import React, { PureComponent } from "react";
import { Tabs, Input, Table, message } from "antd";
import { Carousel } from "react-responsive-carousel";
import classnames from "classnames";
import NoticeBar from "../../components/notice-bar";
import ReconnectingWebSocket from "../../utils/ReconnectingWebSocket";
import { WS_PREFIX } from "../../utils/constants";
import AwardPopup from "./AwardPopup";
import { fixedZero } from "../../utils/index";

import "./carousel.css";
import "./home.css";

/* import partner1 from "../../assets/images/partner/bixin.png";
import partner2 from "../../assets/images/partner/bi.png";
import partner3 from "../../assets/images/partner/nodecape.png";
import partner5 from "../../assets/images/partner/lianwen.png"; */

const TabPane = Tabs.TabPane;
const Search = Input.Search;

class Home extends PureComponent {
  state = {
    banners: [],
    market: "",
    sortedInfo: null,
    tradeExpair: null,
    searchValue: "",
    favoriteCoins: localStorage.getItem("favoriteCoins")
      ? JSON.parse(localStorage.getItem("favoriteCoins"))
      : [],
    total: "",
    relayData: "",
    awardPopup: "",
    remainSecond: 0,
    selectedItem: 0
  };

  request = window.request;

  componentWillMount() {
    this.getBanner();
    this.getTradeExpair();
    this.getTotal();
  }

  componentDidMount() {
    this.openHomeSocket();
    this.openRealySocket();
  }

  componentWillUnmount() {
    clearInterval(this.homeInterval);
    this.homeWS && this.homeWS.close();

    clearInterval(this.relayInterval);
    this.realyWS && this.realyWS.close();

    clearInterval(this.clockInterval);
  }

  getTotal = () => {
    this.request("/mk2/total/info", {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        this.setState({ total: json.data });
      } else {
        message.error(json.msg);
      }
    });
  };

  openClockInterval = () => {
    this.clockInterval = setInterval(() => {
      const { remainSecond } = this.state;
      if (remainSecond && remainSecond > 0) {
        this.setState({ remainSecond: remainSecond - 1 });
      }
    }, 1000);
  };

  openRealySocket = () => {
    this.realyWS = new ReconnectingWebSocket(`${WS_PREFIX}/relay`);

    /* this.realyWS.onopen = () => {
      if (this.realyWS.readyState === 1) {
        this.realyWS.send("getData");
      }
    };
    this.relayInterval = setInterval(() => {
      if (this.realyWS.readyState === 1) {
        this.realyWS.send("getData");
      }
    }, 1000 * 5); */

    this.realyWS.onmessage = evt => {
      const relayData = JSON.parse(evt.data);
      if (relayData) {
        const { remainSecond, isActivity } = relayData;

        if (this.clockInterval) {
          // interval 存在  活动关闭
          if (isActivity === "0") {
            clearInterval(this.clockInterval);
          }
        } else {
          // interval不存在  并且 活动开始
          if (isActivity === "1") {
            this.openClockInterval();
          } else {
            clearInterval(this.clockInterval);
          }
        }
        /* const myRemainSecond = this.state.remainSecond;
        if (myRemainSecond && myRemainSecond > 0) {
        } else {
          this.setState({ remainSecond });
        } */
        this.setState({ relayData, remainSecond });
      }
    };
    this.realyWS.onerror = () => {
      clearInterval(this.clockInterval);
      this.setState({ remainSecond: "" });
    };
  };

  // 主页homeSocket
  openHomeSocket = () => {
    this.homeWS = new ReconnectingWebSocket(`${WS_PREFIX}/home`);

    this.homeInterval = setInterval(() => {
      if (this.homeWS.readyState === 1) {
        this.homeWS.send("ping");
      }
    }, 1000 * 30);

    this.homeWS.onmessage = evt => {
      if (evt.data === "pong") {
        return;
      }

      const { tradeExpair } = this.state;
      const updateExPair = JSON.parse(evt.data);
      if (tradeExpair) {
        Object.keys(updateExPair).forEach(key => {
          if (updateExPair[key]) {
            updateExPair[key].forEach(coin => {
              const expair = `${coin.coinOther}/${coin.coinMain}`;
              if (tradeExpair[key][expair]) {
                tradeExpair[key][expair] = {
                  ...coin,
                  rise: coin.rise || "0.00%",
                  latestPrice: (coin.latestPrice || 0).toFixed(8),
                  highestPrice: (coin.highestPrice || 0).toFixed(8),
                  lowerPrice: (coin.lowerPrice || 0).toFixed(8),
                  dayCount: (coin.dayCount || 0).toFixed(8)
                };
              }
            });
          }
        });
      }
    };
  };

  //获取banner图
  getBanner = () => {
    this.request("/cms/banner/list", {
      method: "GET",
      body: {
        language: "zh_CN"
      }
    }).then(json => {
      if (json.code === 10000000) {
        // /userfiles/1/_thumbs/images/cms/advert/2018/06/banner01.jpg
        let result = json.data.map(item => {
          let { image } = item;
          item.image = image.replace(/\/_thumbs/, "");
          return item;
        });
        this.setState({ banners: result });
      } else {
        message.error(json.msg);
      }
    });
  };

  // 市场币种列表
  getTradeExpair = () => {
    this.setState({ tradeExpair: null });
    this.request("/index/allTradeExpair", {
      method: "GET"
    }).then(json => {
      if (json.code === 10000000) {
        const tradeExpair = {};
        let market = "";
        if (Object.keys(json.data).length > 0) {
          market = Object.keys(json.data)[0];
          Object.keys(json.data).forEach(key => {
            tradeExpair[key] = {};
            json.data[key].forEach(coin => {
              const expair = `${coin.coinOther}/${coin.coinMain}`;
              tradeExpair[key][expair] = {
                ...coin,
                rise: coin.rise || "0.00%",
                latestPrice: (coin.latestPrice || 0).toFixed(8),
                highestPrice: (coin.highestPrice || 0).toFixed(8),
                lowerPrice: (coin.lowerPrice || 0).toFixed(8),
                dayCount: (coin.dayCount || 0).toFixed(8)
              };
            });
          });
        }
        this.setState({ market, tradeExpair });
      } else {
        message.error(json.msg);
      }
    });
  };

  handleSwitchMarkets = market => {
    this.setState({ market, searchList: null, searchValue: "" });
  };

  //收藏币种
  handleCollect = (record, event) => {
    event.stopPropagation();
    const { favoriteCoins } = this.state;
    let newFavoriteCoins;
    if (favoriteCoins.indexOf(record.key) > -1) {
      newFavoriteCoins = favoriteCoins.filter(key => key !== record.key);
    } else {
      newFavoriteCoins = [...favoriteCoins, record.key];
    }
    this.setState({ favoriteCoins: newFavoriteCoins });
    localStorage.setItem("favoriteCoins", JSON.stringify(newFavoriteCoins));
  };

  // 币种排序
  handleSort = (pagination, filters, sorter) => {
    console.log("Various parameters", pagination, filters, sorter);
    this.setState({ sortedInfo: sorter });
  };

  // 跳转到交易中心
  handleGoToTrade = record => {
    localStorage.setItem("tradePair", `${record.coinOther}_${record.coinMain}`);
    this.props.history.push("/trade");
  };

  // 搜索币
  handleSearch = event => {
    this.setState({ searchValue: event.target.value });
  };

  closeModal = () => {
    this.setState({ awardPopup: "" });
  };

  //显示 弹窗
  showAward = () => {
    this.setState({
      awardPopup: <AwardPopup onCancel={this.closeModal} />
    });
  };

  carouselChange = page => {
    this.setState({ selectedItem: page });
  };

  render() {
    const { localization } = this.props;
    let {
      banners,
      market,
      sortedInfo,
      tradeExpair,
      searchValue,
      favoriteCoins,
      total,
      relayData,
      awardPopup,
      remainSecond,
      selectedItem
    } = this.state;

    const { lastMiningCoinVolumeTotal, lastBestHoldCoinVolume } = total;
    const {
      poolVolume = "----",
      prizeVolume = "----",
      winners,
      candidates,
      awardDate,
      isActivity,
      isRemit
    } = relayData;

    sortedInfo = sortedInfo || {};

    let pairList = [];
    let allTradeMarket = [];
    if (tradeExpair && Object.keys(tradeExpair).length > 0) {
      allTradeMarket = Object.keys(tradeExpair);
      allTradeMarket.unshift("optional");
      if (market === "optional") {
        Object.keys(tradeExpair).forEach(market => {
          const coins = Object.keys(tradeExpair[market]).map((key, value) => {
            tradeExpair[market][key].key = key;
            return tradeExpair[market][key];
          });
          pairList = [...pairList, ...coins];
        });
        pairList = pairList.filter(coin => {
          return favoriteCoins.indexOf(coin.key) > -1;
        });
      } else {
        pairList = tradeExpair[market]
          ? Object.keys(tradeExpair[market]).map(key => {
              tradeExpair[market][key].key = key;
              return tradeExpair[market][key];
            })
          : [];
      }
    }

    // 根据搜索关键字筛选
    if (searchValue) {
      pairList = pairList.filter(coin => {
        return coin.coinOther.indexOf(searchValue.toLocaleUpperCase()) !== -1;
      });
    }

    const columns = [
      {
        title: localization["币种"],
        dataIndex: "coinOther",
        key: "coinOther",
        sorter: (a, b) => a.coinOther.charCodeAt() - b.coinOther.charCodeAt(),
        sortOrder: sortedInfo.columnKey === "coinOther" && sortedInfo.order,
        render: (text, record) => (
          <span
            className={classnames({
              "name-wrap": true
            })}
          >
            <i
              className={`iconfont icon-shoucang${
                favoriteCoins.indexOf(record.key) > -1 ? "-active" : ""
              }`}
              onClick={this.handleCollect.bind(this, record)}
            />
            {text}/{record.coinMain}
          </span>
        )
      },
      {
        title: `${localization["最新价"]}${
          market !== "optional" ? `(${market})` : ""
        }`,
        dataIndex: "latestPrice",
        key: "latestPrice",
        sorter: (a, b) => a.latestPrice - b.latestPrice,
        sortOrder: sortedInfo.columnKey === "latestPrice" && sortedInfo.order
      },
      {
        title: localization["涨跌幅"],
        dataIndex: "rise",
        key: "rise",
        sorter: (a, b) =>
          Number(a.rise.substring(0, a.rise.length - 1)) -
          Number(b.rise.substring(0, b.rise.length - 1)),
        sortOrder: sortedInfo.columnKey === "rise" && sortedInfo.order,
        render: text => (
          <span
            className={`font-color-${
              text.indexOf("-") !== -1 ? "red" : "green"
            }`}
          >
            {text}
          </span>
        )
      },
      {
        title: localization["最高价"],
        dataIndex: "highestPrice",
        key: "highestPrice"
      },
      {
        title: localization["最低价"],
        dataIndex: "lowerPrice",
        key: "lowerPrice"
      },
      {
        title: `${localization["成交量"]}`,
        dataIndex: "dayCount",
        key: "dayCount",
        sorter: (a, b) => a.dayCount - b.dayCount,
        sortOrder: sortedInfo.columnKey === "dayCount" && sortedInfo.order
      }
    ];

    let formatRemainSecond = "----";
    if (remainSecond > 0) {
      let hour = parseInt(remainSecond / 60);
      hour = fixedZero(hour);

      let minute = remainSecond % 60;
      minute = fixedZero(minute);

      formatRemainSecond = `${hour}分${minute}秒`;
    }

    return (
      <div className="content home">
        <Carousel
          autoPlay
          infiniteLoop
          selectedItem={selectedItem}
          onChange={page => {
            this.carouselChange(page);
          }}
          stopOnHover
          showArrows={false}
          showStatus={false}
          showThumbs={false}
        >
          {banners.length > 0 &&
            banners.map(banner => {
              if (banner.link) {
                return (
                  <a key={banner.id} href={banner.link} target="_blank">
                    <img
                      key={banner.id}
                      src={banner.image}
                      alt="虚拟资产交易所"
                    />
                  </a>
                );
              } else {
                return (
                  <div key={banner.id}>
                    <img
                      key={banner.id}
                      src={banner.image}
                      alt="虚拟资产交易所"
                    />
                  </div>
                );
              }
            })}
        </Carousel>

        <div className="content-inner" style={{ marginTop: 10 }}>
          <NoticeBar {...{ localization }} />
        </div>
        {
          <ul className="home-awards">
            <li className="mining">
              <i className="iconfont icon-btc" />
              <h3>
                <p className="hold">昨日挖矿总量</p>
                <div>
                  {lastMiningCoinVolumeTotal
                    ? (lastMiningCoinVolumeTotal * 1).toFixed(2)
                    : "----"}
                  <span>UES</span>
                </div>
                <p className="area">昨日最佳持币算力</p>
                <div>
                  {lastBestHoldCoinVolume
                    ? (lastBestHoldCoinVolume * 1).toFixed(2)
                    : "----"}
                  <span>UES</span>
                </div>
              </h3>
            </li>
            <li className="award">
              <i className="iconfont icon-USDT" />
              <h3>
                <p style={{ marginBottom: 20 }}>
                  近一期接力撞奖获得者({" "}
                  {winners && winners.length > 0 ? awardDate : "无人中奖"} )
                </p>

                {winners &&
                  winners.map((item, index) => {
                    return (
                      <div style={{ fontSize: 18, marginTop: 6 }} key={index}>
                        {item.username}

                        <span style={{ marginLeft: 10, color: "#D39F5E" }}>
                          {item.isRefer === "0" ? " 获奖人: " : " 推荐人: "}
                          {prizeVolume} UES
                        </span>
                      </div>
                    );
                  })}

                {winners &&
                  winners.length > 0 && (
                    <a
                      style={{
                        marginTop: 20,
                        textAlign: "right",
                        paddingRight: 20
                      }}
                      onClick={this.showAward}
                    >
                      查看更多奖期 >>
                    </a>
                  )}
                {/* <div className="count">
                  {prizeVolume ? prizeVolume : "----"} <span>UES</span>
                </div> */}
              </h3>
            </li>
            <li className="gainer">
              <i className="iconfont icon-eth" />
              <h3>
                <div>
                  <span>接力撞奖</span>
                  <span className="count">
                    {poolVolume ? poolVolume : "----"}
                  </span>
                </div>
                {isActivity === "0" ? (
                  <p>未在活动时间内</p>
                ) : (
                  <p>倒计时: {formatRemainSecond}</p>
                )}
                <dl>
                  {candidates &&
                    candidates.map((item, index) => {
                      return (
                        <dd key={index}>
                          <span>{item.username}</span>
                          <span>{item.achieveDate}</span>
                        </dd>
                      );
                    })}
                </dl>
              </h3>
            </li>
          </ul>
        }
        <div className="content-inner home-markets">
          <div className="coins-market">
            <Tabs
              size="small"
              tabBarExtraContent={
                <Search
                  value={searchValue}
                  placeholder={localization["输入关键字"]}
                  onChange={this.handleSearch}
                  style={{ width: 200 }}
                />
              }
              activeKey={market}
              onChange={this.handleSwitchMarkets}
            >
              {allTradeMarket &&
                allTradeMarket.map(curMarket => (
                  <TabPane
                    tab={
                      curMarket === "optional" ? (
                        <span>
                          <i
                            className={`iconfont icon-shoucang${
                              market === "optional" ? "-active" : ""
                            }`}
                          />
                          {localization["自选"]}
                        </span>
                      ) : (
                        `${curMarket} ${localization["市场"]}`
                      )
                    }
                    key={curMarket}
                  >
                    <Table
                      size="middle"
                      columns={columns}
                      dataSource={pairList}
                      onChange={this.handleSort}
                      onRow={record => ({
                        onClick: this.handleGoToTrade.bind(this, record)
                      })}
                      locale={{
                        emptyText: (
                          <span>
                            <i className="iconfont icon-zanwushuju" />
                            {localization["暂无数据"]}
                          </span>
                        )
                      }}
                      pagination={false}
                    />
                  </TabPane>
                ))}
            </Tabs>
          </div>
        </div>
        {/*  <div className="partner">
          <div className="partner-inner">
            <h2>-{localization["合作伙伴"]}-</h2>
            <ul className="content-inner">
              <li>
                <a
                  href="https://po.im/#/home"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img src={partner1} alt="" />
                </a>
              </li>
              <li>
                <a
                  href="https://www.magicw.net/"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img src={partner2} alt="" />
                </a>
              </li>
              <li>
                <a
                  href="http://www.nodecap.com/"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img src={partner3} alt="" />
                </a>
              </li>
              <li>
                <a
                  href="https://www.chainnews.com/"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  <img src={partner5} alt="" />
                </a>
              </li>
            </ul>
          </div>
        </div> */}
        {awardPopup}
      </div>
    );
  }
}

export default Home;
